package cn.wolfcode.p2p.base.util;

import cn.wolfcode.p2p.base.exception.CustomerException;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class ExceptionControllerAdvice {

    // 对指定的异常进行处理
    @ExceptionHandler(RuntimeException.class)
    public String handle(Exception ex, Model model){
        model.addAttribute("ex", ex.getMessage());
        // 跳转到处理异常的视图
        return "error";
    }
    // 自定义异常
    @ExceptionHandler(CustomerException.class)
    @ResponseBody
    public Object customer(Exception ex){
        JSONResult result = new JSONResult();
        result.mark(ex.getMessage());
        return result;
    }

    // 自定义异常
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JSONResult handleJSONException(BindException bindEx){
        JSONResult result = new JSONResult();
        List<ObjectError> allErrors = bindEx.getAllErrors();
        StringBuffer sb = new StringBuffer();
        for (ObjectError error : allErrors){
            sb.append(error.getDefaultMessage());
        }
        result.mark(sb.toString());
        return result;
    }

}



